﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Script.Serialization;

namespace Module
{
    public static class JsonMethods
    {
        public static List<Dictionary<string, object>> DataTableToDictionaries(DataTable table)
        {
            var list = new List<Dictionary<string, object>>();

            foreach (DataRow row in table.Rows)
            {
                var dict = new Dictionary<string, object>();

                foreach (DataColumn col in table.Columns)
                {
                    dict[col.ColumnName] = row[col];
                }
                list.Add(dict);
            }
            return list;
        }

        public static Dictionary<string, object> DataSetToDictionaries(DataSet ds)
        {
            return ds.Tables.Cast<DataTable>().ToDictionary<DataTable, string, object>(tb => tb.TableName, DataTableToDictionaries);
        }

        public static string ToJsonString(DataTable table)
        {
            var obj = DataTableToDictionaries(table);
            var js = new JavaScriptSerializer { MaxJsonLength = int.MaxValue };
            return js.Serialize(obj);
        }

        public static string ToJsonString(DataSet dataset)
        {
            var obj = DataSetToDictionaries(dataset);
            var js = new JavaScriptSerializer();
            return js.Serialize(obj);
        }
    }
}
